package com.app.project.manager;

import com.app.project.common.ErrorCode;
import com.app.project.exception.BusinessException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.app.project.config.CosClientConfig;
import java.io.File;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * Cos 对象存储操作
 *
 * @author 
 * @from 
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key 唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载文件到本地
     * @param key 文件key
     * @param localFile 本地文件
     */
    public void getObject(String key, File localFile) {
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
            cosClient.getObject(getObjectRequest, localFile);
        } catch (Exception e) {
            log.error("下载文件失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }

    /**
     * 删除文件
     * @param key 文件key
     */
    public void deleteObject(String key) {
        try {
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
        } catch (Exception e) {
            log.error("删除文件失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败");
        }
    }

    /**
     * 检查文件是否存在
     * @param key 文件key
     * @return 是否存在
     */
    public boolean doesObjectExist(String key) {
        try {
            return cosClient.doesObjectExist(cosClientConfig.getBucket(), key);
        } catch (Exception e) {
            log.error("检查文件是否存在失败, key: {}", key, e);
            return false;
        }
    }

}
